var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
var cors = require("cors");
var indexRouter = require("./routes/index");
var adminRouter = require("./routes/admin");
var textRouter = require("./routes/text");

// 添加一个居民表
var peopleRouter = require("./routes/people")
// 机构xxxx表
var organRouter = require("./routes/organ")
// 上传图片
var uploadRouter = require('./routes/upload')
// gpt聊天记录
var chatgptRouter = require("./routes/chatgpt");
// 获取所有管理员医生
var doctorRouter = require('./routes/user')
// 用户列表
var userRouter = require("./routes/user");
// web聊天
var webchatRouter = require('./routes/webchat')
//居民个人信息d
var personRouter = require("./routes/person_info")
var app = express();

app.use(express.json({ limit: "5000kb" })); // post请求体数据大小限制

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");
app.use(cors());
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/api/public', express.static(path.join(__dirname, "public")));
app.use('/api/uploads', express.static(path.join(__dirname, "uploads")));
// 静态图片机构存放
app.use('/uploads/organ', express.static("uploads/organ"));
// 聊天头像存放
app.use('/uploads', express.static("uploads"));

app.use("/api", indexRouter);
app.use("/api", adminRouter);
app.use("/api", textRouter);
app.use("/api", peopleRouter)
app.use("/api", organRouter)
app.use("/chatgpt", chatgptRouter);
app.use("/doctor", doctorRouter);
app.use("/user", userRouter);
app.use("/api/webchat", webchatRouter);
app.use("/upload", uploadRouter);
app.use("/personinfo", personRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

/**
 * WebSocket模块
 */
// 存储在线的ws对象 
const WsList = [];
const WsIdList = [];
const { WebSocketServer } = require('ws');
const wss = new WebSocketServer({ port: 5678 });
wss.on("connection", function connection(ws, req) {
  ws.send("连接成功")
  id = req.url.split("=")[1]
  if (id.indexOf('%20') >= 0) {
    id = id.replace(/%20/g, " ");
  }
  console.log('转换后的字段', id); // "hello world"
  ws["id"] = id
  if (WsIdList.indexOf(id) == -1) {
    WsIdList.push(id) //一端
    WsList.push(ws) //另一端
    console.log(1, WsIdList);
  }
  // 监听客户端发过来的消息
  ws.on("message", function message(data, isBinary) {
    console.log('信息流', JSON.parse(data.toString()));
    const message = JSON.parse(data)

    WsList.forEach(item => {
      if (item.id == message.toId) {
        console.log(JSON.stringify(message));
        console.log("发送消息成功");
        item.send(JSON.stringify(message))
      }
    })
  })
})

module.exports = app;
